package com.crawler.uc.listener;

import com.alibaba.fastjson.JSONObject;
import com.crawler.component.SpringContextUtil;
import com.crawler.listener.RedisPubSubListener;
import com.crawler.rest.security.services.impl.UserCenterBearerTokenCacheService;
import com.crawler.rest.security.services.impl.UserCenterMacTokenCacheService;
import com.crawler.rest.support.Constants;
import com.crawler.uc.config.UcConstant;
import com.crawler.uc.push.PushBody;
import com.crawler.uc.push.event.KickEvent;
import com.crawler.uc.utils.UcRedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 配置 消息监听器
 * @author rubekid
 *
 * 2017年1月5日 上午11:38:18
 */
public class UCPubSubListener extends RedisPubSubListener {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
    
	@Override  
    public void onMessage(String channel, String message) {
		System.out.println(message);
		try{
			if(UcConstant.PUSH_CHANNEL.equals(channel)){
				PushBody body = UcRedisManager.parse(message, PushBody.class);
				if(body != null){
					String data = JSONObject.toJSONString(body.getData());
					KickEvent event = JSONObject.parseObject(data, KickEvent.class);
					if(Constants.AUTHORIZATION_TYPE_MAC.equals(event.getType())){
						UserCenterMacTokenCacheService userCenterMacTokenCacheService = SpringContextUtil.getBean(UserCenterMacTokenCacheService.class);
						userCenterMacTokenCacheService.removeCache(event.getAccessToken());
					}
					else if(Constants.AUTHORIZATION_TYPE_BEARER.equals(event.getType())){
						UserCenterBearerTokenCacheService userCenterBearerTokenCacheService = SpringContextUtil.getBean(UserCenterBearerTokenCacheService.class);
						userCenterBearerTokenCacheService.removeCache(event.getAccessToken());
					}
					
				}
			}
		}
		catch(RuntimeException ex){
			logger.error(ex.getMessage());
		}
		
    }  
} 